package com.ftg.learn.chapter8.pattern.singleton.thread;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 不安全
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/8/2 下午3:26
 */
public class LockWithOur {

    private static int a = 0;

    //可重入锁
    private static Lock lock = new ReentrantLock();


    private static void add() {

        lock.lock();
        try{
            // 表示代码进行执行操作 如果出现问题走catch
            a++;
        }catch (Exception e){
            //我发现try里面出现错误后走到这里
        }finally{
            //表示在方法 结束以前一定会走一次
            lock.unlock();
        }

    }

    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                add();
            }
        });


        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                add();
            }
        });

        //计时 时间 値
        long s1 = System.currentTimeMillis();
        t1.start();
        t2.start();

//        并发数  : 高并发

        // main结束
        //捕获处理 try chatch
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("出错了");
            e.printStackTrace();
        }

        System.out.println(a);
        long s2 = System.currentTimeMillis();
        //0 -20000

        System.out.println("用时==>" + (s2 - s1));
    }

}
